#!/usr/bin/env node

//后台模板渲染 在浏览器192.168.189.131:3000   
//或者在浏览器192.168.189.131:3000/?
const http = require('http');

http.createServer((req, res) => {
    console.log(req.url);
    res.setHeader('Access-Control-Allow-Origin', '*');//跨域策略的设置
    let url = new URL(req.url, `http://${req.headers.host}`);
    console.log(url);
    if(req.url === '/') {
        res.end(emptyPage());
        return;
    }
    if(url.search !== '') {
        res.end(resultPage(url));
        return;
    }
    res.end(errPage());
}).listen(3000);

function errPage() {
    return '<body><h1>Not Found!</h1></body>';

}

const html = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>矩形计算器</title>
        <style>
            label {
                display: inline-block;
                width: 50px;
                height:30px;
            }
            span {
                display:inline-block;
                border:1px solid black;
                width:170px;
                height:20px;
        </style>
    </head>
    <body>
        <form method="GET" action="">
            <label>宽度：</label>
            <input type="text" name="width" value="__width" />
            <br />
            <label>高度：</label>
            <input type="text" name="height" value="__height"/>
            <br />
            <label> </label>
            <input type="submit" value="计算"/>
            <br />
            <label>周长：</label>
            <span>perimeter</span>
            <br />
            <label>面积：</label>
            <span>area</span>
            <br />
        </form>
    </body>
    </html>
`;
function emptyPage() {
    return html.replace('area', '')
    .replace('perimeter', '')
    .replace('__width', '')
    .replace('__height', '');
}
function resultPage(url) {
    const width = Number(url.searchParams.get('width'));
    const height = Number(url.searchParams.get('height'));
    
    const rect = {
        area:width * height,
        perimeter: 2 * (width + height),
    };

    return html.replace('area', rect.area)
    .replace('perimeter', rect.perimeter)
    .replace('__width', width)
    .replace('__height', height);
}


